package 行为型模式.状态;

/**
 * @ClassNameStageTest
 * @Description 环境 -> 抽象状态 具体状态设置环境 （你中有我，我中有你）
 * @Author
 * @Date2022/1/5 11:44
 **/
public class StateTest {
    public static void main(String[] args) {
        Context context = new Context();
        System.out.println("学生成绩状态测试：");
        context.add(30);
        context.add(40);
        context.add(25);
        context.add(-15);
        context.add(-25);

    }
}

// 环境类
class Context {
    private ScoreState scoreState;

    public Context() {
        this.scoreState = new LowState(this);
    }

    public ScoreState getScoreState() {
        return scoreState;
    }

    public void setScoreState(ScoreState scoreState) {
        this.scoreState = scoreState;
    }

    public void add(int score) {
        scoreState.addScore(score);
    }
}

abstract class ScoreState {
    protected Context context;  //环境
    protected String stateName; //状态名
    protected int score; //分数

    public abstract void checkState(); //检查当前状态

    public void addScore(int x) {
        score += x;
        System.out.print("加上：" + x + "分，\t当前分数：" + score);
        checkState();
        System.out.println("分，\t当前状态：" + context.getScoreState().stateName);
    }

}

// 不及格
class LowState extends ScoreState {
    public LowState(Context context) {
        this.context = context;
        stateName = "不及格";
        score = 0;
    }

    public LowState(ScoreState scoreState) {
        context = scoreState.context;
        stateName = "不及格";
        score = scoreState.score;
    }

    @Override
    public void checkState() {
        if (score >= 90) {
            context.setScoreState(new HighState(this));
        } else if (score >= 60) {
            context.setScoreState(new MiddleState(this));
        }
    }
}

//具体状态类：中等
class MiddleState extends ScoreState {
    public MiddleState(ScoreState state) {
        context = state.context;
        stateName = "中等";
        score = state.score;
    }

    @Override
    public void checkState() {
        if (score < 60) {
            context.setScoreState(new LowState(this));
        } else if (score >= 90) {
            context.setScoreState(new HighState(this));
        }
    }
}

//具体状态类：优秀
class HighState extends ScoreState {
    public HighState(ScoreState state) {
        context = state.context;
        stateName = "优秀";
        score = state.score;
    }

    @Override
    public void checkState() {
        if (score < 60) {
            context.setScoreState(new LowState(this));
        } else if (score < 90) {
            context.setScoreState(new MiddleState(this));
        }
    }
}
